package org.tgcloud.group;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;

import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

public class DynamicHeadListener extends AnalysisEventListener<Map<Integer, String>> {

    // 存储所有数据行（表头转换后的 map）
    private final List<Map<String, String>> result = new ArrayList<>();

    // 表头（按列顺序）
    private List<String> headList = new ArrayList<>();

    // 读取表头
    @Override
    public void invokeHeadMap(Map<Integer, String> headMap, AnalysisContext context) {
        headList = headMap.entrySet()
                .stream()
                .sorted(Map.Entry.comparingByKey())   // 保证列顺序正确
                .map(Map.Entry::getValue)
                .collect(Collectors.toList());
    }

    // 读取数据行
    @Override
    public void invoke(Map<Integer, String> row, AnalysisContext context) {
        Map<String, String> map = new LinkedHashMap<>();
        row.entrySet()
                .stream()
                .sorted(Map.Entry.comparingByKey()) // 保证列顺序一致
                .forEach(e -> map.put(headList.get(e.getKey()), e.getValue()));
        result.add(map);
    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext context) {
        // no-op
    }

    public List<Map<String, String>> getResult() {
        return result;
    }
}
